

package com.itheima.controller.backend.security;


import com.itheima.dao.UserDao;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

@Slf4j
@Service
public class SpringSecurityUserService implements UserDetailsService {
    @Autowired
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查询用户
        User user = userDao.loadUserByUsername(username);
        if (user == null) {
            log.info("用户不存在");
            throw new UsernameNotFoundException("用户不存在！");
        }else {
            // 查询用户的角色
            Set<Role> roles = userDao.loadRolesByUserId(user.getId());
            // 设置用户的权限
            user.setRoles(roles);
            return user;
        }
    }
}


